require 'family_tree_api/person/assertions/base'
require 'family_tree_api/person/assertions/person'
require 'family_tree_api/person/assertions/date'
require 'family_tree_api/person/assertions/place'

module FamilyTreeApi
  module Person
    module Assertion
      
      class Event < Base
        attr_accessor :type, :scope, :place, :date, :spouse
        
        def initialize(params = {})
          @notes = []
          @type = params[:type]
          @scope = params[:scope]
          @place = params[:place]
          @date = params[:date]
        end
        
        def ==(other)
          other.kind_of?(Assertion::Event) && 
            @type == other.type &&
            @scope == other.scope &&
            @place == other.place &&
            @date == other.date &&
            @spouse == other.spouse &&
            @notes == other.notes
        end
        
        def place=(place)
          case place
          when FamilyTreeApi::Person::Assertion::Place
            @place = place
          else
            @place = Assertion::Place.new
            @place.original = place
          end
        end
        
        def date=(date)
          case date
          when FamilyTreeApi::Person::Assertion::Date
            @date = date
          else
            @date = Assertion::Date.new
            @date.original = date
          end
        end
        
        def to_xml
          e = super
          e.add_attribute('type', @type)
          e.add_attribute('scope', @scope)
          e.add_element(@date.to_xml) if @date
          e.add_element(@place.to_xml) if @place
          e.add_element(@spouse.to_xml) if @spouse
          e
        end
        
        def self.parse(event_element)
          event = Event.new
          event.parse_attributes(event_element)
          event.type = event_element.attributes["type"]
          event.scope = event_element.attributes["scope"]
          event_element.each do |e|
            case e.name
            when 'date'
              event.date = Assertion::Date.parse(e)
            when 'place'
              event.place = Assertion::Place.parse(e)
            when 'spouse'
              event.spouse = Assertion::Spouse.parse(e)
            end
          end
          event
        end
      end
      
    end
  end
end